package com.zheng.demo.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.util.HashMap;
import java.util.Map;

public class KafkaProducerAsync {
    public static void main(String[] args) {
        Map<String, Object> configMap = new HashMap<>();
        configMap.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        configMap.put(
                ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
                "org.apache.kafka.common.serialization.StringSerializer");
        configMap.put(
                ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
                "org.apache.kafka.common.serialization.StringSerializer");
        KafkaProducer<String, String> producer = new KafkaProducer<>(configMap);
        // 准备数据,定义泛型
        for (int i = 0; i < 10; i++) {
            // 创建数据
            ProducerRecord<String, String> record = new ProducerRecord<>("test", "key" + i, "value" + i);
            //  生产（发送）数据
            producer.send(record, (metadata, e) -> {
                if (e == null) {
                    System.out.println("数据发送成功：" + metadata.timestamp());
                }
            });
            System.out.println("发送数据"); // 先打印"发送数据"，再回调成功信息
        }
        producer.close();
    }
}
